// chat_server.h
#ifndef CHAT_SERVER_H
#define CHAT_SERVER_H

#include <vector>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <string>
#include <unordered_set>  // 用于unordered_set
#include <unordered_map>  // 用于unordered_map
#include <algorithm>      // 用于std::remove_if
#include <atomic>
#include <algorithm>      //用于find_nth来
#include <fcntl.h>        //用来非阻塞
#include "sql_handler.h"
#include "timer_manager.h"



class ChatServer {
private:
    int m_sfd;
    std::vector<std::thread> m_workers;
    std::queue<std::function<void()>> m_tasks;
    std::vector<long long> q_msg_tmp,q_req_tmp,q_user_ol;
    std::unordered_set<long long> online_msg,online_req;
    std::mutex m_taskMutex,m_msg_life,m_msg_dead,m_msg_tmp,m_req_life,m_req_dead,m_req_tmp,m_user_ol,m_id_fd;
    std::condition_variable m_taskCV,c_msg_live,c_msg_dead,c_msg_tmp,c_req_life,c_req_dead,c_req_tmp,c_user_ol;
    std::unordered_map<long long,int> id_fd;
    std::unordered_map<long long,std::vector<long long>> offline_msg,offline_req;
    bool m_stop=false,m_proc_stop=false,m_msg_avail=false;
    SQLHandler m_sqlHandler;
    std::thread m_timer_thd,m_msg_proc_thd;

    TimerManager timer_fetch,timer_proc,timer_online;  // 定时器管理器


    // 恶意协议特征库
    std::unordered_set<std::string> maliciousProtocols = {
        ""//被人攻击了，我不在这写了，你们自己写协议，我服了
    };
    std::unordered_set<std::string> sensitivePaths = {
        ""//自己看情况
    };
    std::unordered_set<std::string> maliciousUserAgents = {
        ""//
    };

    // IP访问频率记录
    std::unordered_map<std::string, std::vector<std::time_t>> ipAccessTimes;
    // 禁止访问的IP列表
    std::unordered_set<std::string> blockedIPs;
    // 最大访问频率（10次/30秒）
    const int MAX_ACCESS_FREQ = 10;
    const int TIME_WINDOW = 30; // 30秒

public:
    ChatServer(const std::string& ip, int port, int threadCount, MySQLConnectionPool& pool);
    
    ~ChatServer();
    void initThreadPool(int threadCount);
    void enqueueTask(std::function<void()> task);
    void start();
    void stop();
    void handleClient(int clientFd);
    bool detectMaliciousProtocol(const std::string& message, const std::string& clientIP);
    bool detectAbnormalFrequency(const std::string& clientIP);
    void handleBlockedRequest(int clientFd, const std::string& clientIP, const std::string& reason); 
    bool detectSqlInjection(const std::string& message);

    size_t FindNthStr(const std::string& source,const std::string& goal,int nth);
    void FetchMsg();
    void FetchReq();
    void SendMsg();
    void SendReq();
    void OnlineMsg();
    void OnlineReq();
    void MoveToTemp();
};

#endif // CHAT_SERVER_H